//
//  CRTool.m
//  CRChatRoom
//
//  Created by lanou3g on 15/11/21.
//  Copyright © 2015年 SecondGroup. All rights reserved.
//

#import "CRTool.h"
#import "CRUserDetailModel.h"
#import "MBProgressHUD+MJ.h"
#import "CRDataTool.h"


@implementation CRTool



/**
 *  从数据库中查询当前用户的好友列表-(查询friends字段-里面有好友分组信息(每个分组中有哪些好友))
 */
+ (void)getAllFriendsWithBlock:(void (^)(NSArray *data))block {
    
    AVQuery *query = [AVQuery queryWithClassName:@"_User"];
    [query getObjectInBackgroundWithId:[AVUser currentUser].objectId block:^(AVObject *object, NSError *error) {
        
        NSDictionary *dict = object[@"friends"];
        // 所有的分组名称
        NSArray *keys = dict.allKeys;
        // 每个分组中所有的好友
        NSArray *valuse = dict.allValues;
        
        NSMutableArray *array = [NSMutableArray array];
        [keys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            // 好友分组组名称
            [dict setObject:obj forKey:@"name"];
            // 好友列表  -- valuse[idx] 是个数组--里面装着字典
            
            NSMutableArray *tempArray = [NSMutableArray array];
            for (NSDictionary *dict in valuse[idx]) {
                // 查询每个好友的头像url(重新赋值)
                //=======
                NSMutableDictionary *muDict = [NSMutableDictionary dictionaryWithDictionary:dict];
                [tempArray addObject:muDict];
            }
            
            [dict setObject:tempArray forKey:@"friends"];
            // 当前用户的用户名
            [dict setObject:object[@"username"] forKey:@"username"];
            [array addObject:dict];
        }];
        
#warning 做缓存操作============
        // 在此做缓存操作
        block(array);
        // 缓存好友列表到本地
        [CRDataTool cacheFriendsWithObject:array];
        
    }];
    
}





/**
 *  从数据库中查找当前用户以及所有好友所发的信息内容
 */
+ (void)getAllSpaceContentWithBlock:(void (^)(NSArray *))block
{
    AVUser *curentUser = [AVUser currentUser];
    NSMutableArray *friendsId = curentUser[@"friendsId"];
    [friendsId addObject:[AVUser currentUser].objectId]; // friendsId 中存放所有好友的id以及自己的id
    
    AVQuery *query = [AVQuery queryWithClassName:@"Post"];
    // 按发帖时间降序排列
    [query orderByDescending:@"createdAt"];
    [query whereKey:@"userID" containedIn:friendsId];//
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            // 回调block
            block(objects);
            // 在此缓存空间动态内容到本地
#warning =====在此缓存空间动态内容到本地==直接缓存spaceFrame数组-暴力
//            [CRDataTool cacehSpaceWithObject:objects];

            
        } else {
            // 输出错误信息
            NSLog(@"Error: %@ %@", error, [error userInfo]);
        }
    }];

}
/**
 *  存储用户个人信息到服务器
 *
 */
+ (void)saveUserInfoWithUserDetailModel:(CRUserDetailModel *)model
{
    
    AVUser *user = [AVUser currentUser];
    NSMutableDictionary *muDict = [NSMutableDictionary dictionary];

    if (model.iconImage) {
        NSData *imageData = UIImagePNGRepresentation(model.iconImage);
        AVFile *imageFile = [AVFile fileWithName:@"image.png" data:imageData];
        [user setObject:imageFile forKey:@"icon"];
    }
    
    // 个性签名
    [muDict setValue:user.username forKey:@"username"];
    [muDict setValue:model.signature forKey:@"signature"];
    // 昵称
    [muDict setValue:model.remarkName forKey:@"remarkName"];
    // 性别
    [muDict setValue:model.gender forKey:@"gender"];
    // 年龄
    [muDict setValue:model.age forKey:@"age"];
    // 生日
    [muDict setValue:model.brithday forKey:@"brithday"];
    // 工作
    [muDict setValue:model.job forKey:@"job"];
    // 公司
    [muDict setValue:model.company forKey:@"company"];
    // 学校
    [muDict setValue:model.school forKey:@"school"];
    // 住址
    [muDict setValue:model.address forKey:@"address"];
    // 家乡
    [muDict setValue:model.hometown forKey:@"hometown"];
    // 兴趣
    [muDict setValue:model.hobby forKey:@"hobby"];
    
    [user setObject:muDict forKey:@"userinfo"];
    
    
    [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (!error) {
            [MBProgressHUD showSuccess:@"修改信息成功"];
        } else {
            [MBProgressHUD showError:@"修改信息失败"];
        }
    }];
    
    
}

/**
 *  返回用户的个人信息-用于显示在个人信息编辑页面
 *
 *  @param block
 */
+ (void)getUserInfoWithobjectId:(NSString *)objectId withblock:(void (^)(NSDictionary *))block
{
    AVQuery *query = [AVQuery queryWithClassName:@"_User"];
    [query whereKey:@"objectId" equalTo:objectId];
    
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[object objectForKey:@"userinfo"]];
        // 发送的图片
        AVFile *pics = [object objectForKey:@"icon"];
        [dict setValue:pics.url forKey:@"iconUrl"];
        // 回调
        block(dict);
    }];
    
    
}

/**
 *  获得所有的评论内容
 */
+ (void)getallCommentsWithObjectId:(NSString *)objectId withblock:(void (^)(NSArray *))block
{
    AVQuery *query = [AVQuery queryWithClassName:@"Post"];
    [query whereKey:@"objectId" equalTo:objectId];
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {

        block(object[@"Usercontent"]);
        
    }];
        
        
}

/**
 *  根据用户的username来添加好友
 */
+ (void)addFriendWithUsername:(NSString *)username
{
    
    AVUser *user = [AVUser currentUser];
    NSArray *friendArray = user[@"friendsId"];
    // 当前用户的好友列表信息
    NSDictionary *friends = user[@"friends"];
    // 根据username查到好友的objectId
    AVQuery *query = [AVUser query];
    [query whereKey:@"username" equalTo:username];
    AVObject *obj = [query getFirstObject];    // 好友的那条信息
    // 要添加的好友的objectId
    NSString *otherObjId = obj[@"objectId"];
    AVFile *file = obj[@"icon"];
    NSString *iconUrl = file.url;  // 好友的头像地址
    // 好友的信息字典
//    NSDictionary *other = @{@"username" : username, @"objectId" : otherObjId, @"iconUrl": iconUrl};
    NSMutableDictionary *other = [NSMutableDictionary dictionary];
    [other setValue:username forKey:@"username"];
    [other setValue:otherObjId forKey:@"objectId"];
    [other setValue:iconUrl forKey:@"iconUrl"];
    
    if (!obj) {   // 如果没有此用户 直接返回
        [MBProgressHUD showError:@"没有此用户"];
        return;
    }
    
    
    
    if (friendArray.count == 0) {   // 如果没有一个好友
        [user setObject:@[otherObjId] forKey:@"friendsId"];

        [MBProgressHUD showSuccess:@"添加好友成功"];
        // 添加好友到friends中-里面有分组信息
#warning 待实现=================BUG 必须有一个好友之后才能添加

//            NSArray *tempAray = @[other];
////        NSMutableDictionary *frind = [NSMutableDictionary dictionaryWithDictionary:friends];
//        NSDictionary *dict = @{@"好友" : tempAray};
////            [frind setValue:tempAray forKey:@"好友"];
//            [user setObject:dict forKey:@"friends"];
//            [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//                NSLog(@"%@", error);
//            }];
        
        NSArray *temp = friends[@"好友"];
        NSMutableArray *muArray = [NSMutableArray arrayWithArray:temp];
        [muArray addObject:other];
        NSMutableDictionary *friend = [NSMutableDictionary dictionaryWithDictionary:friends];
        [friend setObject:muArray forKey:@"好友"];
        [user setObject:friend forKey:@"friends"];

         [user saveInBackground];
        
        
            return ;
        
    } else { // 有好友用户-并且当前用户的好友列表不为空
        
        if ([friendArray containsObject:otherObjId]) {
            [MBProgressHUD showSuccess:@"已经是好友了"];
            return;
        } else {
            [MBProgressHUD showSuccess:@"添加好友成功"];
            // 存objectId 到friendArray 中
            NSMutableArray *muFriend = [NSMutableArray arrayWithArray:friendArray];
            [muFriend addObject:otherObjId];
            
            NSArray *temp = friends[@"好友"];
            NSMutableArray *muArray = [NSMutableArray arrayWithArray:temp];
            [muArray addObject:other];
            NSMutableDictionary *friend = [NSMutableDictionary dictionaryWithDictionary:friends];
            [friend setObject:muArray forKey:@"好友"];
            [user setObject:friend forKey:@"friends"];
            [user setObject:muFriend forKey:@"friendsId"];
            [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            }];
            
        }
    }
    
    
}


/**
 *  把当前用户的地理位置保存到服务器
 */
+ (void)saveUserLocation
{
    
#warning 待优化---让用户传入一个位置
    // 只要已进入这个界面就先把自己的位置更新到服务器
    AVGeoPoint *point = [AVGeoPoint geoPointWithLatitude:51 longitude:116.4];
    
    AVQuery *query = [AVQuery queryWithClassName:@"LocationInfo"];
    [query whereKey:@"userID" equalTo:[AVUser currentUser].objectId];
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        
        // 创建一条记录插入表中
        AVObject *location = [AVObject objectWithClassName:@"LocationInfo"];
        // 把位置存入
        [location setObject:point forKey:@"location"];
        // 存放用户基本信息的字典- userDict
        NSMutableDictionary *userDict = [NSMutableDictionary dictionary];
        [userDict setValue:[AVUser currentUser].objectId forKey:@"objectId"];
        [userDict setValue:[AVUser currentUser].username forKey:@"username"];
        AVFile *file = [[AVUser currentUser] objectForKey:@"icon"];
        [userDict setValue:file.url forKey:@"iconUrl"];
        // 把用户基本信息存入
        [location setObject:userDict forKey:@"userinfo"];
        // 把用户的objectId存入作为查询的唯一标记
        [location setObject:[AVUser currentUser].objectId forKey:@"userID"];
        
        // 如果表中还没有记录  -就把当前用户的地址 username objectId iconUrl 存入表中
        if (!object) {
            [location saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {

            }];
        } else {  // 表中有记录--就更新一下位置和个人基本信息
            
            [object setObject:point forKey:@"location"];
            [object setObject:userDict forKey:@"userinfo"];
            [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {

            }];
        }
        
    }];

}

/**
 *  查找附近的人
 */
+ (void)findNearPersonWith:(void (^)(NSArray *))block
{
    AVQuery *userquery = [AVQuery queryWithClassName:@"LocationInfo"];
    [userquery whereKey:@"userID" equalTo:[AVUser currentUser].objectId];
    [userquery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        // 先查到自己的位置
        AVGeoPoint *userLocation =  (AVGeoPoint *) [object objectForKey:@"location"];
        //获取最接近用户地点的人
        AVQuery *query = [AVQuery queryWithClassName:@"LocationInfo"];
        [query whereKey:@"location" nearGeoPoint:userLocation];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            // 回调
            block(objects);
            
        }];
        
    }];
    

}



/**
 *  用户刚注册的时候初始化用户的表
 */
+ (void)initTabelData
{
    // 表中有一个好友就是自己--
    AVUser *user = [AVUser currentUser];
//    AVFile *file = user[@"icon"];
    NSArray *friendsId = @[user.objectId];
    // 当前用户的信息
//    NSDictionary *dict = @{@"username" : user.username, @"iconUrl" : file.url, @"objectId" : user.objectId};
    NSDictionary *userInfo = @{@"朋友" : @[], @"好友" : @[]};
    [user setObject:friendsId forKey:@"friendsId"];
    [user setObject:userInfo forKey:@"friends"];
    [user saveInBackground];
    
}




@end











